package com.sean.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sean.common.utils.PageUtils;
import com.sean.common.utils.Query;
import com.sean.common.utils.R;
import com.sean.gulimall.product.dao.BrandDao;
import com.sean.gulimall.product.entity.BrandEntity;
import com.sean.gulimall.product.entity.CategoryBrandRelationEntity;
import com.sean.gulimall.product.service.BrandService;
import com.sean.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;




@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                new QueryWrapper<BrandEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void updateDetails(BrandEntity brand) {
        //更新品牌
        this.updateById(brand);
        //更新关联表
        CategoryBrandRelationEntity  relationEntity = new CategoryBrandRelationEntity();
        relationEntity.setBrandName(brand.getName());
        categoryBrandRelationService.update(relationEntity,
                new LambdaUpdateWrapper<CategoryBrandRelationEntity>()
                        .eq(CategoryBrandRelationEntity::getBrandId,brand.getBrandId()));
    }

    @Override
    public R removeCascaderByIds(List<Long> ids) {
        //删除前先判断关联表
        for (Long id :ids)
        {
            LambdaQueryWrapper<CategoryBrandRelationEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CategoryBrandRelationEntity::getBrandId,id);
            long count = categoryBrandRelationService.count(wrapper);
            if(count > 0)
            {
                return R.error("该商品使用中，请检查其关联关系");
            }
        };
        this.removeByIds(ids);
        return R.ok();
    }
}